#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import os

from common.const import CMDResult
from common.logger import Logger
from common.util.exec_utils import exec_cp_cmd, su_exec_cat_cmd, exec_cat_cmd
from informix.comm.comm import execute_cmd, mkdir_set_permissions
from informix.comm.const import InformixInfo

log = Logger().get_logger("informix.log")


class CommonCommand:
    @staticmethod
    def informix_execute_cmd(cmd):
        return_code, out_info, err_info = execute_cmd(cmd)
        ret = (return_code == CMDResult.SUCCESS.value)
        if not ret:
            err_msg = f"execute return_code: {return_code}, out_info:{out_info}, err_info:{err_info}"
            if "user informix does not exist" in err_info:
                log.warn(err_msg)
            else:
                log.error(err_msg)
        res_cont = out_info if ret else err_info
        return ret, res_cont

    @staticmethod
    def cat_file(file_path):
        if os.path.islink(file_path):
            log.error("The path is a soft link.")
            return False, ""
        # 文件内容大于60M不使用该方法
        if os.path.getsize(file_path) > 60 * 1048576:
            log.error("The file size exceeds 60 MB.")
            return False, ""
        ret, result = exec_cat_cmd(file_path)
        return ret, result

    @staticmethod
    def copy_file(src_path_list, target_path, db_user=InformixInfo.INFORMIX_USER):
        for src_path in src_path_list:
            ret = exec_cp_cmd(src_path, target_path, db_user, None)
            if not ret:
                log.error(f"Failed to copy {src_path} to {target_path}. ret: {ret};")
                return ret, ''
        return True, "Copy file successfully."

    @staticmethod
    def open_file_grep(file_path, target):
        target_list = []
        if not os.path.exists(file_path):
            return target_list
        with open(file_path, "r") as file:
            text = file.readlines()
            for line in text:
                if target in line:
                    target_list.append(line)
        return target_list

    @staticmethod
    def create_dir(dir_path, user=InformixInfo.INFORMIX_USER):
        return mkdir_set_permissions(dir_path, user)
